<template>
    <div class="app-container">
      <el-card class="box-card">
        <div slot="header" class="clearfix">
          <span class="header-title">{{ isEdit ? '修改巡区' : '新增巡区' }}</span>
          <div class="header-actions">
            <el-button type="primary" @click="saveArea" :loading="saving">保存巡区</el-button>
            <el-button @click="goBack">返回列表</el-button>
          </div>
        </div>
  
        <el-row :gutter="20">
          <!-- 左侧表单 -->
          <el-col :span="8">
            <el-form ref="form" :model="form" :rules="rules" label-width="120px">
              <el-form-item label="巡区名称" prop="areaName">
                <el-input v-model="form.areaName" placeholder="请输入巡区名称" />
              </el-form-item>
              
              <el-form-item label="巡区编号" prop="areaCode">
                <el-input v-model="form.areaCode" placeholder="请输入巡区编号" />
              </el-form-item>
              
              <el-form-item label="所属部门" prop="deptId">
                <treeselect
                  v-model="form.deptId"
                  :options="deptOptions"
                  :normalizer="normalizer"
                  :show-count="true"
                  placeholder="选择所属部门"
                />
              </el-form-item>
              
              <el-form-item label="巡区类型" prop="areaType">
                <el-radio-group v-model="form.areaType">
                  <el-radio :label="1">常规区域</el-radio>
                  <el-radio :label="2">重点区域</el-radio>
                </el-radio-group>
              </el-form-item>
              
              <el-form-item label="巡区状态" prop="status">
                <el-radio-group v-model="form.status">
                  <el-radio :label="0">正常</el-radio>
                  <el-radio :label="1">停用</el-radio>
                </el-radio-group>
              </el-form-item>
              
              <el-form-item label="设置电子围栏" prop="hasFence">
                <el-switch
                  v-model="form.hasFence"
                  active-text="是"
                  inactive-text="否"
                />
              </el-form-item>
              
              <el-form-item label="备注" prop="remark">
                <el-input v-model="form.remark" type="textarea" :rows="3" placeholder="请输入备注信息" />
              </el-form-item>
            </el-form>
          </el-col>
  
          <!-- 右侧地图区域 -->
          <el-col :span="16">
            <div class="map-section">
              <div class="map-controls">
                <el-button type="primary" size="small" @click="startDraw" :disabled="!mapReady">
                  <i class="el-icon-edit"></i> 开始绘制
                </el-button>
                <el-button type="warning" size="small" @click="clearDraw" :disabled="!mapReady">
                  <i class="el-icon-delete"></i> 清除绘制
                </el-button>
                <el-button type="success" size="small" @click="finishDraw">
                  <i class="el-icon-check"></i> 完成绘制
                </el-button>
                <el-button type="info" size="small" @click="resetMap" :disabled="!mapReady">
                  <i class="el-icon-refresh"></i> 重置地图
                </el-button>
              </div>
              
              <div class="map-info">
                <el-alert
                  v-if="!mapReady"
                  title="地图加载中..."
                  type="info"
                  :closable="false"
                  show-icon
                />
                <el-alert
                  v-else-if="!currentOverlay"
                  title="请点击开始绘制按钮，然后在地图上绘制巡区范围"
                  type="warning"
                  :closable="false"
                  show-icon
                />
                <el-alert
                  v-else
                  :title="`已绘制巡区范围，共 ${currentOverlay ? currentOverlay.getPath().length : 0} 个点`"
                  type="success"
                  :closable="false"
                  show-icon
                />
              </div>
              
              <div ref="mapContainer" class="map-container"></div>
            </div>
          </el-col>
        </el-row>
      </el-card>
    </div>
  </template>
  
  <script>
  import AMapLoader from '@amap/amap-jsapi-loader';
  import { getPatrolArea, addPatrolArea, updatePatrolArea } from '@/api/system/patrolArea';
  import { deptTreeSelect } from '@/api/system/user';
  import Treeselect from '@riophae/vue-treeselect';
  import '@riophae/vue-treeselect/dist/vue-treeselect.css';
  
  export default {
    name: 'PatrolAreaDraw',
    components: { Treeselect },
    data() {
      return {
        // 是否为编辑模式
        isEdit: false,
        // 保存中状态
        saving: false,
        // 地图是否准备就绪
        mapReady: false,
        // 地图实例
        map: null,
        // 绘制工具
        mouseTool: null,
        // 当前绘制的覆盖物
        currentOverlay: null,
        // 部门树选项
        deptOptions: [],
        // 表单参数
        form: {
          areaId: undefined,
          areaName: '',
          areaCode: '',
          areaType: 1,
          hasFence: false,
          status: 0,
          area: [],
          deptId: undefined,
          remark: ''
        },
        // 表单校验规则
        rules: {
          areaName: [
            { required: true, message: '巡区名称不能为空', trigger: 'blur' }
          ],
          areaCode: [
            { required: true, message: '巡区编号不能为空', trigger: 'blur' }
          ],
          deptId: [
            { required: true, message: '请选择所属部门', trigger: 'change' }
          ],
          areaType: [
            { required: true, message: '请选择巡区类型', trigger: 'change' }
          ],
          area: [
            { 
              validator: (rule, value, callback) => {
                console.log('验证巡区范围，当前值:', value);
                console.log('当前覆盖物:', this.currentOverlay);
                
                // 如果有覆盖物但form.area为空，说明还没有完成绘制
                if (this.currentOverlay && (!value || value.length === 0)) {
                  callback(new Error('请点击"完成绘制"按钮确认巡区范围'));
                  return;
                }
                
                if (!value || value.length === 0) {
                  callback(new Error('请先绘制巡区范围'));
                } else if (value.length < 3) {
                  callback(new Error('巡区范围至少需要3个点'));
                } else {
                  callback();
                }
              }, 
              trigger: 'change' 
            }
          ]
        }
      };
    },
    computed: {
      // 完成绘制按钮是否可用
      canFinishDraw() {
        return this.currentOverlay !== null && this.currentOverlay !== undefined;
      }
    },
    created() {
      // 获取路由参数
      const areaId = this.$route.query.areaId;
      if (areaId) {
        this.isEdit = true;
        this.loadAreaData(areaId);
      }
      
      // 获取部门树
      this.getDeptTree();
    },
    mounted() {
      this.initMap();
    },
    beforeDestroy() {
      if (this.map) {
        this.map.destroy();
      }
    },
    methods: {
      /** 初始化地图 */
      async initMap() {
        try {
          const AMap = await AMapLoader.load({
            key: '4b98d24146ee2f4b43cc046b7886cb71',
            version: '2.0',
            plugins: ['AMap.ToolBar', 'AMap.Scale', 'AMap.MouseTool', 'AMap.PolyEditor']
          });
  
          // 创建地图实例
          this.map = new AMap.Map(this.$refs.mapContainer, {
            zoom: 12,
            center: [114.085947, 22.547],
            viewMode: '3D'
          });
  
          // 添加地图控件
          this.map.addControl(new AMap.ToolBar());
          this.map.addControl(new AMap.Scale());
  
          // 初始化鼠标工具
          this.mouseTool = new AMap.MouseTool(this.map);
          
          // 监听绘制完成事件
          this.mouseTool.on('draw', (event) => {
            this.currentOverlay = event.obj;
            console.log('绘制完成，currentOverlay:', this.currentOverlay);
            this.$message.success('绘制完成，可以点击完成绘制确认');
            // 强制更新视图
            this.$forceUpdate();
          });
          
          this.mapReady = true;
          console.log('地图初始化成功');
          
          // 如果是编辑模式，加载现有巡区数据
          if (this.isEdit && this.form.area && this.form.area.length > 0) {
            this.loadExistingArea();
          }
        } catch (e) {
          console.error('地图加载失败', e);
          this.$message.error('地图加载失败，请刷新页面重试');
        }
      },
      
      /** 加载现有巡区数据 */
      loadExistingArea() {
        if (!this.map || !this.form.area || this.form.area.length === 0) return;
        
        let path = this.form.area;
        if (typeof this.form.area === 'string') {
          try {
            path = JSON.parse(this.form.area);
          } catch (e) {
            console.error('巡区坐标数据格式错误:', this.form.area);
            return;
          }
        }
        
        if (this.validateCoordinates(path)) {
          this.currentOverlay = new AMap.Polygon({
            path: path,
            strokeColor: '#FF33FF',
            strokeWeight: 2,
            strokeOpacity: 0.9,
            fillColor: '#1791fc',
            fillOpacity: 0.3
          });
          this.map.add(this.currentOverlay);
          this.map.setFitView([this.currentOverlay]);
          this.$message.success('已加载现有巡区范围');
        }
      },
      
      /** 开始绘制 */
      startDraw() {
        if (!this.mapReady || !this.mouseTool) {
          this.$message.warning('地图未初始化，请稍后重试');
          return;
        }
        
        this.clearDraw();
        this.mouseTool.polygon({
          strokeColor: '#FF33FF',
          strokeWeight: 2,
          strokeOpacity: 0.9,
          fillColor: '#1791fc',
          fillOpacity: 0.3
        });
        this.$message.success('请在地图上绘制巡区范围');
      },
      
      /** 清除绘制 */
      clearDraw() {
        if (this.currentOverlay) {
          this.map.remove(this.currentOverlay);
          this.currentOverlay = null;
        }
        if (this.mouseTool) {
          this.mouseTool.close();
        }
        this.form.area = [];
      },
      
      /** 完成绘制 */
      finishDraw() {
        console.log('点击完成绘制按钮，currentOverlay:', this.currentOverlay);
        if (!this.currentOverlay) {
          this.$message.warning('请先绘制巡区范围');
          return;
        }
        
        const path = this.currentOverlay.getPath();
        console.log('获取到的路径:', path);
        if (path && path.length >= 3) {
          this.form.area = path.map(point => [point.lng, point.lat]);
          this.$message.success(`巡区范围绘制完成，共 ${path.length} 个点`);
          
          // 触发表单验证更新
          this.$nextTick(() => {
            this.$refs['form'].validateField('area');
          });
        } else {
          this.$message.error('巡区范围数据无效');
        }
      },
      
      /** 重置地图 */
      resetMap() {
        this.clearDraw();
        this.map.setZoom(12);
        this.map.setCenter([114.085947, 22.547]);
      },
      
      /** 加载巡区数据 */
      loadAreaData(areaId) {
        getPatrolArea(areaId).then(response => {
          this.form = response.data;
          // 确保数据类型正确
          this.form.hasFence = this.form.hasFence === 1 || this.form.hasFence === true;
          this.form.areaType = parseInt(this.form.areaType) || 1;
          this.form.status = parseInt(this.form.status) || 0;
          
          // 处理area字段：如果是JSON字符串，解析为数组
          if (this.form.area && typeof this.form.area === 'string') {
            try {
              this.form.area = JSON.parse(this.form.area);
            } catch (e) {
              console.error('解析巡区坐标数据失败:', e);
              this.form.area = [];
            }
          }
        }).catch(() => {
          this.$message.error('加载巡区数据失败');
          this.goBack();
        });
      },
      
      /** 获取部门树 */
      getDeptTree() {
        deptTreeSelect().then(response => {
          this.deptOptions = response.data;
        });
      },
      
      /** 格式化部门树数据 */
      normalizer(node) {
        return {
          id: node.id,
          label: node.label,
          children: node.children
        };
      },
      
      /** 保存巡区 */
      saveArea() {
        console.log('开始保存巡区，当前表单数据:', this.form);
        console.log('当前绘制的覆盖物:', this.currentOverlay);
        
        // 如果还没有完成绘制，但已经有覆盖物，先完成绘制
        if (this.currentOverlay && (!this.form.area || this.form.area.length === 0)) {
          console.log('检测到有覆盖物但未完成绘制，自动完成绘制');
          this.finishDraw();
        }
        
        this.$refs['form'].validate(valid => {
          if (valid) {
            // 再次检查是否绘制了巡区范围
            if (!this.form.area || this.form.area.length === 0) {
              console.log('表单验证通过，但巡区范围为空:', this.form.area);
              this.$message.error('请先绘制巡区范围');
              return;
            }
            
            console.log('准备提交数据:', this.form);
            this.saving = true;
            
            // 转换数据格式
            const submitData = this.convertFormData(this.form);
            console.log('转换后的提交数据:', submitData);
            
            const savePromise = this.isEdit 
              ? updatePatrolArea(submitData)
              : addPatrolArea(submitData);
              
            savePromise.then(response => {
              this.$modal.msgSuccess(this.isEdit ? '修改成功' : '新增成功');
              this.goBack();
            }).catch((error) => {
              console.error('保存失败:', error);
              this.$message.error('保存失败');
            }).finally(() => {
              this.saving = false;
            });
          } else {
            console.log('表单验证失败');
          }
        });
      },
      
      /** 数据转换工具 */
      convertFormData(formData) {
        return {
          ...formData,
          hasFence: formData.hasFence ? 1 : 0,
          areaType: parseInt(formData.areaType) || 1,
          status: parseInt(formData.status) || 0,
          deptId: formData.deptId ? parseInt(formData.deptId) : null,
          areaId: formData.areaId ? parseInt(formData.areaId) : null,
          // 将坐标数组转换为JSON字符串
          area: Array.isArray(formData.area) ? JSON.stringify(formData.area) : formData.area
        };
      },
      
      /** 验证坐标数据 */
      validateCoordinates(coordinates) {
        if (!Array.isArray(coordinates)) {
          return false;
        }
        
        for (let coord of coordinates) {
          if (!Array.isArray(coord) || coord.length < 2) {
            return false;
          }
          
          const [lng, lat] = coord;
          if (isNaN(lng) || isNaN(lat) || 
              lng < -180 || lng > 180 || 
              lat < -90 || lat > 90) {
            return false;
          }
        }
        
        return coordinates.length >= 3;
      },
      
      /** 返回列表 */
      goBack() {
        this.$router.push('/patrol/area');
      }
    }
  };
  </script>
  
  <style lang="scss" scoped>
  .app-container {
    .box-card {
      .header-title {
        font-size: 18px;
        font-weight: bold;
      }
      
      .header-actions {
        float: right;
      }
    }
    
    .map-section {
      .map-controls {
        margin-bottom: 15px;
        display: flex;
        gap: 10px;
        flex-wrap: wrap;
        
        .el-button {
          margin: 0;
        }
      }
      
      .map-info {
        margin-bottom: 15px;
      }
      
      .map-container {
        height: 600px;
        width: 100%;
        border-radius: 4px;
        overflow: hidden;
        border: 1px solid #dcdfe6;
      }
    }
    
    .el-form {
      .el-form-item {
        margin-bottom: 20px;
      }
    }
  }
  </style> 